<?php

namespace Mouta\AmistateBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Mouta\AmistateBundle\utils\SfSolr;
use Mouta\AmistateBundle\utils\Thumbnail;


class AdminGlobalController extends Controller
{
    public function headerAction($id = null)
    {
        $estadisticas = $this->getDoctrine()->getEntityManager()->getRepository('AmistateBundle:Usuario')->getEstadisticas();
        return $this->render('AmistateBundle:adminGlobal:header.html.twig',array(
            'estadisticas'=>$estadisticas,
        ));
    }
    
    public function reindexarAction($auto)
    {
        if($auto){
            $em = $this->getDoctrine()->getEntityManager();
            $users = $em->createQuery('SELECT u FROM AmistateBundle:Usuario u WHERE u.reindexar = 1')->setMaxResults(100)->getResult();
            foreach($users as $user){
                $solr = new SfSolr();
                $solr->AddOrUpdateUser($user);
                $user->setReindexar(0);
                $em->persist($user);
            }
            $em->flush();
            die;
        }
        $defaultData = array('cantidad' => '20');
        $form = $this->createFormBuilder($defaultData)
            ->add('cantidad','text')
            ->getForm();
        if($this->getRequest()->getMethod() == "POST"){
            $form->bindRequest($this->getRequest());
            $cant = $form->get('cantidad')->getData();
            
            $em = $this->getDoctrine()->getEntityManager();
            $users = $em->createQuery('SELECT u FROM AmistateBundle:Usuario u WHERE u.reindexar = 1')->setMaxResults($cant)->getResult();
            foreach($users as $user){
                $solr = new SfSolr();
                $solr->AddOrUpdateUser($user);
                $user->setReindexar(0);
                $em->persist($user);
            }
            $em->flush();
        }
        return $this->render('AmistateBundle:adminGlobal:reindexar.html.twig',array(
            'form' => $form->createView(),
            ));
    }
    
    private function validar(){
        $request = $this->getRequest();
        
        if($request->get('nombre') == "")
            die("nombre invalidos");
        
        if($request->get('control_u_pais') == "")
            die("pais invalidos");
        
        if($request->get('control_u_latitude') == "")
            die("latitude invalidos");
        
        if($request->get('control_u_longitude') == "")
            die("longitude invalidos");
        
        if($request->get('email') == "")
            die("email invalidos");
        
        if($request->get('sexo') == "")
            die("sexo invalidos");
        
        if($request->get('busco') == "")
            die("busco invalidos");
        
        if($request->get('para') == "")
            die("para invalidos");
        
        if($request->get('cumple') == "")
            die("cumple invalidos");
        
        if($request->get('descripcion') == "")
            die("descripcion invalidos");
        
        if(strlen($request->get('descripcion')) < 25)
            die("descripcion muy corta minimo 25 caracteres");
    }
    
    public function migrarAction($usuario){
        $con = mysql_connect("localhost","root","apolo113");
        if (!$con)
            die('Could not connect: ' . mysql_error());

        
        if($usuario>0){
            $request = $this->getRequest();
            $sql = "SELECT * FROM soysexy.usuario syu inner join soysexy.usuario_opcional syuo on syu.id = syuo.id WHERE syu.email not in (SELECT amu.email FROM amistate2.usuario amu) AND syu.id = $usuario";
            //var_dump($sql);die;
            $usuarios = array();
            $result = mysql_query($sql);

            while($row = mysql_fetch_array($result))
                $unusuario = $row;
            
            foreach($unusuario as $key=>$value){
                $unusuario[$key] = utf8_decode($value);
            }
            
            $imagenes = array();
            $sql = "SELECT * FROM soysexy.usuario_imagen syu WHERE syu.usuario_id = $usuario";
            $result = mysql_query($sql);
            if($result){
                while($row = mysql_fetch_array($result)){
                    $imagenes[] = $row;
                }
                    
            }
            
            mysql_close($con);
            
            
            if($request->getMethod() == 'POST'){
                $user = new \Mouta\AmistateBundle\Entity\Usuario();
                $this->validar();
                $oldId = $request->get('oldid');
                $user->setNombre($request->get('nombre'));
                $user->setApellido($request->get('apellido'));
                
                $user->setPais($request->get('control_u_pais'));
                $user->setProvincia($request->get('control_u_provincia'));
                $user->setCiudad($request->get('control_u_ciudad'));
                
                $user->setSeoPais(\Mouta\AmistateBundle\utils\Strings::getSeoUrl($request->get('control_u_pais')));
                $user->setSeoProvincia(\Mouta\AmistateBundle\utils\Strings::getSeoUrl($request->get('control_u_provincia')));
                $user->setSeoCiudad(\Mouta\AmistateBundle\utils\Strings::getSeoUrl($request->get('control_u_ciudad')));
                
                $user->setLatitude($request->get('control_u_latitude'));
                $user->setLongitude($request->get('control_u_longitude'));
                $user->setUsername($request->get('email'));
                $user->setUsernameCanonical($request->get('email'));
                $user->setEmail($request->get('email'));
                $user->setEmailCanonical($request->get('email'));
                $user->setEnabled(0);
                $user->setEmailCanonical($request->get('email'));
                
                $user->setPlainPassword("pdyw823ndfvs04gbxcmwiedfj");
                $user->setSexo($request->get('sexo'));
                $user->setBusco($request->get('busco'));
                $user->setPara($request->get('para'));
                $user->setCumple(\DateTime::createFromFormat('Y-m-d', $request->get('cumple')));
                $user->setDescripcion($request->get('descripcion'));
                $user->setFbId($request->get('fb_id'));
                $user->setMusica($request->get('musica'));
                
                $user->setPeliculas($request->get('peliculas'));
                $user->setLibros($request->get('libros'));
                $user->setApellido($request->get('apellido'));
                $user->setTele($request->get('tele'));
                $user->setDeportes($request->get('deportes'));
                $user->setTrabajo($request->get('trabajo'));
                $user->setFrase($request->get('frase'));
                $user->setBuscas($request->get('buscas'));
                $user->setComida($request->get('comida'));
                $user->setFacebook($request->get('facebook'));
                
                $em = $this->getDoctrine()->getEntityManager();
                $em->persist($user);
                $em->flush();
                
                try {
                    foreach($imagenes as $imagen){
                        $img = new \Mouta\AmistateBundle\Entity\ImagenUsuario();

                        $urlImage = 'http://soy-sexy.com.ar/web/uploads/1/'.$oldId.'/'. $imagen['imagen_big'];
                        $image = file_get_contents($urlImage);
                        file_put_contents($_SERVER['DOCUMENT_ROOT']."/upload/tmp/".$imagen['imagen_big'], $image);
                        $urlImage = $_SERVER['DOCUMENT_ROOT']."/upload/tmp/".$imagen['imagen_big'];


                        $thumbnail = new Thumbnail($urlImage);
                        $thumbnail->Thumbnail($urlImage);

                        $errorT = false;
                        if(empty ($thumbnail->error_msg))
                        {
                            $thumbnail->size_auto(90);
                            $thumbnail->process();
                        }else{
                            $errorT = true;
                        }

                        $bigThumbnail = new Thumbnail($urlImage);
                        $bigThumbnail->Thumbnail($urlImage);
                        if(empty ($bigThumbnail->error_msg))
                        {
                            $bigThumbnail->size_auto(600);
                            $bigThumbnail->process();
                        }else{
                            $errorT = true;
                        }

                        if(!$errorT)
                        {
                            $thumbnail->save($this->getPathImage($user->getId())."t-".$imagen['imagen_big']);
                            $bigThumbnail->save($this->getPathImage($user->getId())."".$imagen['imagen_big']);

                            $img->setCreatedAt(date_create_from_format('d/m/Y', date('d/m/Y')));
                            $img->setLabel($imagen['label']);
                            $img->setUsuario($user);
                            $img->setImagen('t-'.$imagen['imagen_big']);
                            $img->setImagenBig($imagen['imagen_big']);
                            $em->persist($img);
                            $em->flush();
                        }
                    }
                    $this->container->get('amistate.user_manager')->actualizarUser($user);
                    $em->getRepository('AmistateBundle:ImagenUsuario')->actualizarDefault($user->getId());
                    
                } catch (Exception $exc) {
                    $em->remove($user);
                }

                
            }
            
            return $this->render('AmistateBundle:adminGlobal:migrarEdit.html.twig',array(
                'usuario' => $unusuario,
                'imagenes' => $imagenes,
            ));
        } else {
            
            $sql = "SELECT * FROM soysexy.usuario syu inner join soysexy.usuario_opcional syuo on syu.id = syuo.id WHERE syu.email not in (SELECT amu.email FROM amistate2.usuario amu)";
            $usuarios = array();
            $result = mysql_query($sql);

            while($row = mysql_fetch_array($result))
            {
                foreach($row as $key=>$value){
                    $row[$key] = utf8_decode($value);
                }

                $usuarios[] = $row;

            }
            mysql_close($con);
            
            return $this->render('AmistateBundle:adminGlobal:migrar.html.twig',array(
                'usuarios' => $usuarios
            ));
        }
        
    }
    
    private function getPathImage($usuario_id){
        $folder = ceil($usuario_id / 1000);
        $dir = $_SERVER['DOCUMENT_ROOT']."/upload/".$folder.'/'.$usuario_id.'/';
        if( !is_dir($dir) )
            mkdir($dir,0777,true);
        return $dir;
    }
    
}
